<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class School extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 如果是超管，就跳转到超管的控制器
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载库
        $this->load->model('schoolModel');
        $this->load->model('staffModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
    }

    // 后台首页
	public function index() {
        // 如果是单点登录，且携带了module参数
        if($this->session->intensiveModule){
            // show_404();
        }
        //获取首页统计信息
        $indexData = $this->_get_index_data();
        // $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "index");
        $this->displayWithData(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "index", $indexData);
	}

    // 教师管理
    public function teacher(){
        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        // 角色数据源
        $this->roleDatasource = $this->staffModel->get_role_tree_datasource($this->rmxSchool['id'], false);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "teacher");
    }
    // 获取教师列表
    public function get_teacher_list(){
        $this->load->model('wxUserModel');
        // 学生姓名筛选
        if($this->get("keyword")) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        // 是否绑定
        if($this->get("bind")) $totalParams['bind'] = $data['bind'] = trim($this->get("bind"));

        // var_export($this->get("keyword"));
        // var_export($this->get("bind"));
        // exit;

        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->schoolModel->get_teacher_list_join_bind($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        $data['orderBy'] = '`id` DESC';
        $teacherList = $this->schoolModel->get_teacher_list_join_bind($data);
        // 获取微信用户列表
        $wxUserList = $this->wxUserModel->get_wx_user_list();
        // 使用id作为键值
        $wxUserList = array_value_to_key($wxUserList, 'id');
  
        // 获取教师其他信息
        foreach($teacherList as &$teacher) {
            $teacher['role'] = $this->staffModel->get_role_by_role_set($teacher['role_id_set']);
            // // 查询任课班级
            // $params['classId'] = $teacher['class_ids'];
            // // 过滤软删除
            // $params['isDelete'] = 0;
            // $teacher['classList'] = $this->classesModel->get_grade_class_list($params);

            // 获取微信绑定人列表
            $bindParams['isDelete'] = 0;
            $bindParams['bindUserId'] = $teacher['id'];
            $bindParams['bindUserType'] = BIND_TYPE_TEACHER;
            $bindUserList = $this->wxUserModel->get_bind_user_list($bindParams);
            if($bindUserList) {
                $nicknameArr = array();
                foreach($bindUserList as $bindUser) {
                    if(isset($wxUserList[$bindUser['wx_user_id']])) {
                        $nickname = $wxUserList[$bindUser['wx_user_id']]['nickname'];
                        if($nickname) {
                            array_push($nicknameArr, urldecode($nickname));
                        }
                    }
                }
            }

            $bindHtmlArr = array();
            if($bindUserList) {
                $bindArr = array();
                foreach($bindUserList as $bindUser) {
                    if(isset($wxUserList[$bindUser['wx_user_id']])) {
                        $nickname = $wxUserList[$bindUser['wx_user_id']]['nickname'];
                        if($nickname) {
                            array_push($bindArr, array(
                                'id' => $bindUser['id'],
                                'nickname' => urldecode($nickname)
                            ));

                            $bindHtmlArr[] = '<a href="javascript:;" class="unbind" data-id="' . $bindUser['id'] . '" >' . urldecode($nickname) . '</a>';
                        }
                    }
                }
            }

            if($bindHtmlArr) {
                $teacher['bindUsers'] = implode('&nbsp;&nbsp;&nbsp;&nbsp;', $bindHtmlArr);
            } else {
                $teacher['bindUsers'] = '';
            }
        }
        // 返回值
        exit(admin_table_data($total, $teacherList));
    }
    // 导出教师数据
    public function export_teacher() {
        // 学生姓名筛选
        if($this->get("keyword")) $data['keyword'] = trim($this->get("keyword"));
        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        $data['orderBy'] = '`id` DESC';
        $teacherList = $this->schoolModel->get_teacher_list($data);
        $firstRow = array(
            '教师名称',
            '角色',
            '性别',
            '登录账号',
            '联系电话'
        );
        $exportData[] = $firstRow;
        // 获取教师其他信息
        foreach($teacherList as &$teacher) {
            $teacher['role'] = $this->staffModel->get_role_by_role_set($teacher['role_id_set']);
            $teacher['roleName'] = implode(',', $teacher['role']);
            $exportData[] = array(
                $teacher['realname'],
                $teacher['roleName'],
                $teacher['gender'],
                $teacher['username'],
                $teacher['mobile']
            );
        }
        $widthParams = array(
            array(
                'index' => 'B',
                'width' => 20
            ),
            array(
                'index' => 'D',
                'width' => 20
            ),
            array(
                'index' => 'E',
                'width' => 20
            )
        );
        exportExcel('教师数据表', $exportData, $widthParams);
    }
    // 编辑/修改教师
    public function teacher_edit($teacherId = 0){
        $this->teacherId = $teacherId;
        $teacherInfo = $this->schoolModel->get_teacher_info($teacherId);
        // 去掉已删除的role_id
        $roleList = $this->staffModel->get_role_list($teacherInfo['school_id']);
        $roleList = array_value_to_key($roleList, 'id');
        if($teacherInfo['role_id_set']) {
            $roleIdArr = explode(',', $teacherInfo['role_id_set']);
            $newRoleIdArr = array();
            foreach($roleIdArr as $roleId) {
                if(isset($roleList[$roleId])) {
                    array_push($newRoleIdArr, $roleId); 
                }
            }

            $teacherInfo['role_id_set'] = implode(',', $newRoleIdArr);
        }

        $this->teacherInfo = $teacherInfo;
        if($teacherId && (!$teacherInfo || $teacherInfo['school_id'] != $this->rmxSchool['id'])) show_error("参数错误，请刷新后重试");
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        // 角色数据源
        $this->roleDatasource = $this->staffModel->get_role_tree_datasource($this->rmxSchool['id'], false);

        // 年级班级列表
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 只获取行政班
        $params['classType'] = CLASSES_TYPE_NORMAL;
        $this->gradeArray = $this->classesModel->get_grade_class_list($params);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "teacher_edit");
    }
    // 保存老师
    public function save_teacher_action(){
        $this->load->model('accountModel');

        $teacherId = $this->post("id");
        $teacherName = trim($this->post("teacher_name"));
        $mobile = $this->post("mobile");
        $headimgurl = $this->post("headimgurl") ? $this->post("headimgurl") : '';
        $faceimage = $this->post("faceimage") ? $this->post("faceimage") : '';
        $username = trim($this->post("username"));
        // 权限可为空
        $roleIdSet = $this->post("role_id_set") ? $this->post("role_id_set") : '';
        // // 任课班级可为空
        // $teacherClass = $this->post("teacher_class") ? $this->post("teacher_class") : '';

        // 内容检测
        if(!$teacherName) throw new Exception("请填写教师名称");
        if(!str_is_username($username)) throw new Exception("请填写正确的账号格式");
        if($mobile && !str_is_mobile($mobile)) throw new Exception("请填写正确的手机号码");
        // if(!$headimgurl) throw new Exception("请上传教师头像");
        // if(!$roleIdSet) throw new Exception("请选择教师角色");
        // 检查登录账号是否存在
        $adminInfo = $this->accountModel->check_username_exists_exclude_admin($this->rmxSchool['id'], $username, $teacherId, USER_TYPE_TEACHER);
        if($adminInfo) throw new Exception("账号已存在，请重新输入");
        // 入库
        $data['username'] = $username;
        $data['realname'] = $teacherName;
        $data['mobile'] = $mobile;
        $data['gender'] = $this->post("gender");
        $data['headimgurl'] = $headimgurl;
        $data['face_image'] = $faceimage;
        $data['content'] = $this->post("content", false);
        $data['role_id_set'] = $roleIdSet;
        // $data['class_ids'] = $teacherClass;
        $data['updatetime'] = date("Y-m-d H:i:s");
        $msg = $teacherId ? '修改教师信息成功' : '添加教师成功';
        // 人脸图片是否改动
        $faceImageChange = false;
        // 闸机任务类型
        $taskType = GATE_TASK_TYPE_ADD;
        // 是否更新
        $isUpdate = false;
        if($teacherId) {
            // 更新操作
            $teacherInfo = $this->schoolModel->get_teacher_info($teacherId);
            if($teacherInfo['face_image'] != $data['face_image']) {
                $faceImageChange = true;
                if($teacherInfo['face_image'] != '') {
                    $taskType = GATE_TASK_TYPE_UPDATE;
                }
            }
            $this->db->update(SchoolModel::$schoolUserTable, $data,"id='{$teacherId}'");
            $isUpdate = true;
        } else {
            if($data['face_image']) {
                $faceImageChange = true;
            }

            $data['school_id'] = $this->rmxUser['school_id'];
            $data['user_type'] = USER_TYPE_TEACHER;
            $data['password'] = password_hash(123456, PASSWORD_DEFAULT);

            $data['createtime'] = $data['updatetime'];
            $this->db->insert(SchoolModel::$schoolUserTable, $data);
            $teacherId = $this->db->insert_id();
        }

        if($faceImageChange) {
            // 插入闸机任务
            $gateParams['schoolId'] = $this->rmxSchool['id'];
            $gateParams['campusId'] = $this->campusInfo['id'];
            // 过滤软删除
            $gateParams['isDelete'] = 0;
            $gateList = $this->schoolModel->get_gate_list($gateParams);
            if($gateList) {
                $insertTaskBatch = array();
                foreach($gateList as $gate) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'gate_id' => $gate['id'],
                        'device_sn' => $gate['device_sn'],
                        'user_id' => $teacherId,
                        'user_name' => $data['realname'],
                        'user_face_image' => $data['face_image'],
                        'user_type' => GATE_USER_TYPE_TEACHER,
                        'task_type' => $taskType,
                        'task_state' => GATE_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
                }
            }
        }    

        // 插入日志
        $this->load->library('logger');
        $actionName = $isUpdate ? 'update' : 'add';
        $actionChineseName = $isUpdate ? '修改' : '增加';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => $actionChineseName . '教师，教师id：' . $teacherId . '，教师名称：' . $teacherName
        ));

        exit(json($msg, true));
    }
    // 重置教师登录密码
    public function reset_teacher_password(){
        $this->load->model('accountModel');
        $userId = $this->get("id");
        // 修改密码
        $save['password'] = password_hash(123456, PASSWORD_DEFAULT);
        $this->db->update(AccountModel::$schoolUserTable, $save,"id='{$userId}'");

        exit(json("重置登录密码成功", true));
    }
    // 选择教师插件数据源
    public function select_teacher_plugin_data_source(){
        // 获取教师列表
        $params['field'] = "`id`, `realname`, `role_id_set`";
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($params);
        foreach($teacherList as $key => $teacher) {
            // 获取首字母
            $teacherList[$key]['realnameFirstChar'] = getFirstChar($teacher['realname']);
        }
        // 按姓名首字母排序
        $timeKey =  array_column($teacherList, 'realnameFirstChar');
        array_multisort($timeKey, SORT_ASC, $teacherList);
        $teacherArray = array();
        foreach($teacherList as $teacher) {
            // 初始化数组
            if(!isset($teacherArray[$teacher['role_id_set']])) $teacherArray[$teacher['role_id_set']] = array();
            // 将老师根据角色分组
            $teacherArray[$teacher['role_id_set']][] = $teacher;
        }
        // 获取角色树状图
        $roleDatasource = array();
        $roleList = $this->staffModel->get_role_list($this->rmxSchool['id']);
        foreach($roleList as $role) {
            $roleId = $role['id'];
            $rolePid = $role['role_parent_id'];
            $roleTree = $role['role_parent_tree'];
            // 关系菜单
            $tree['text'] = '<span>'. $role['role_name'] .'</span>';
            $tree['type'] = 'folder';
            $tree['attr'] = array("id" => $roleId);
            $tree['additionalParameters']['children'] = array();

            // 检查老师是否该角色
            foreach($teacherArray as $role => $teacherData) {
                $roleArray = explode(",", $role);
                // 如果是该角色下的教师
                if(in_array($roleId, $roleArray)) {
                    foreach($teacherData as $teacher) {
                        $teacherInfo['text'] = $teacher['realname'];
                        $teacherInfo['type'] = 'item';
                        $teacherInfo['attr'] = array("id" => $teacher['id']);
                        $tree['additionalParameters']['children'][] = $teacherInfo;
                    }
                }
            }

            // 根据关系树，生成下级关系
            if($roleTree) {
                $treeArray = explode(",", $roleTree);
                $leaveStr = "";
                foreach($treeArray as $parentId) {
                    if($parentId == 0) continue;
                    $leaveStr .= "['label_{$parentId}']['additionalParameters']['children']";
                }
                // 包含到上级角色
                eval("\$roleDatasource{$leaveStr}['label_'. \$roleId] = \$tree;");
            } else {
                $roleDatasource['label_'. $roleId] = $tree;
            }
        }
        exit(json("", true, $roleDatasource));
    }
    // 删除教师
    public function delete_teacher_action() {
        $id = $this->post('id');
        $teacherInfo = $this->schoolModel->get_teacher_info($id);
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(SchoolModel::$schoolUserTable, $data, array('id' => $id));
        // 删除对应的执教关系
        $this->load->model('staffModel');
        $this->db->update(StaffModel::$coachTable, $data, array(
            'teacher_id' => $id,
            'is_delete' => 0
        ));
        // 清除对应科目的schedule_teacher字段
        $this->db->update(ClassesModel::$scheduleLessonTable, array(
            'schedule_teacher' => 0,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'schedule_teacher' => $id,
            'is_delete' => 0
        ));

        if($teacherInfo['face_image']) {
            // 插入闸机任务
            $gateParams['schoolId'] = $this->rmxSchool['id'];
            $gateParams['campusId'] = $this->campusInfo['id'];
            // 过滤软删除
            $gateParams['isDelete'] = 0;
            $gateList = $this->schoolModel->get_gate_list($gateParams);
            if($gateList) {
                $insertTaskBatch = array();
                foreach($gateList as $gate) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'gate_id' => $gate['id'],
                        'device_sn' => $gate['device_sn'],
                        'user_id' => $id,
                        'user_name' => $teacherInfo['realname'],
                        'user_face_image' => $teacherInfo['face_image'],
                        'user_type' => GATE_USER_TYPE_TEACHER,
                        'task_type' => GATE_TASK_TYPE_DELETE,
                        'task_state' => GATE_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
                }
            }
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('delete');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '删除教师，教师id：' . $id . '，教师名称：' . $teacherInfo['realname']
        ));

        exit(json('删除成功', true));
    }

    // 学生管理
    public function student(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);
        // echo'<pre>';var_export($classArray);exit;
        // 获取年级对应的教学班级列表
        $gradeParams['classType'] = CLASSES_TYPE_TEACHING;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeTeachingClassList = json_encode($classArray);

        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);
        // 获取教学班
        $classParams['classType'] = CLASSES_TYPE_TEACHING;
        $this->teachingClassList = $this->classesModel->get_class_list($classParams);
        // 获取选修班
        $classParams['classType'] = CLASSES_TYPE_ELECTIVE;
        $this->electiveClassList = $this->classesModel->get_class_list($classParams);
        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "student");
    }
    // 学生编辑
    public function student_edit($studentId = 0){
        $this->studentId = $studentId;
        $this->studentInfo = $studentInfo = $this->schoolModel->get_student_info($studentId);
        if($studentId && (!$studentInfo || $studentInfo['school_id'] != $this->rmxSchool['id'])) show_error("参数错误，请刷新后重试");
        // 行政班
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['classType'] = CLASSES_TYPE_NORMAL;
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $params['classId'] = $this->rmxUser['class_ids'];
        }
        $this->classList = $this->classesModel->get_class_list($params);
        // 教学班
        $params['isDelete'] = 0;
        $teachParams['schoolId'] = $this->rmxSchool['id'];
        $teachParams['campusId'] = $this->campusInfo['id'];
        $teachParams['classType'] = CLASSES_TYPE_TEACHING;
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $params['classId'] = $this->rmxUser['class_ids'];
        }
        $this->teachClass = $this->classesModel->get_class_list($teachParams);
        // 获取选修班
        $electiveParams['isDelete'] = 0;
        $electiveParams['schoolId'] = $this->rmxSchool['id'];
        $electiveParams['campusId'] = $this->campusInfo['id'];
        $electiveParams['classType'] = CLASSES_TYPE_ELECTIVE;
        $this->electiveClass = $this->classesModel->get_class_list($electiveParams);

        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "student_edit");   
    }
    // 保存学生信息
    public function save_student_action(){
        $this->load->model('accountModel');

        $studentId = $this->post("id");
        $studentName = trim($this->post("realname"));
        $mobile = $this->post("mobile");
        $username = trim($this->post('username'));
        $classId = $this->post("class_id");
        $teachClass = $this->post("teaching_class_id") ? $this->post("teaching_class_id") : "";
        $electiveClass = $this->post("elective_class_id") ? $this->post("elective_class_id") : "";
        $realcard = trim($this->post("realcard"));
        $seatNo = trim($this->post("seatno"));

        // 内容检测
        if(!$studentName) throw new Exception("请填写学生名称");
        if($mobile && !str_is_mobile($mobile)) throw new Exception("请填写正确的联系电话");
        if(!$classId) throw new Exception("请选择学生就读行政班");
        // if(empty($realcard)) throw new Exception("请填写学生物理卡号");
        if($realcard) {
            // 学校内物理卡号唯一
            $student = $this->schoolModel->get_student_info_by_realcard($realcard, $this->rmxUser['school_id'], $studentId);
            if(!empty($student)) {
                throw new Exception('物理卡号已被占用');
            }
        }

        // 检查登录账号是否存在
        if(empty($username)) {
            throw new Exception("学号不能为空");
        }
        $userInfo = $this->accountModel->check_username_exists($this->rmxSchool['id'], $username, $studentId, '');
        if($userInfo) throw new Exception("学号已存在，请重新输入");
        // 检查同班座位号
        if($seatNo) {
            $userInfo = $this->accountModel->check_seatno_exists($classId, $seatNo, $studentId);
            if($userInfo) {
                throw new Exception("同班座位号不能重复");
            }
        }

        // 提示信息
        $msg = $studentId ? '修改学生信息成功' : '添加学生成功';
        // 入库
        $data['campus_id'] = $this->campusInfo['id'];
        $data['class_id'] = $classId;
        $data['realname'] = trim($studentName);
        $data['mobile'] = trim($mobile);
        $data['username'] = $username;
        $data['gender'] = $this->post("gender");
        $data['realcard'] = $realcard;
        $data['job'] = trim($this->post("job"));
        $data['face_image'] = $this->post("face_image");
        $data['teaching_class_id'] = $teachClass;
        $data['elective_class_id'] = $electiveClass;
        $data['seat_no'] = $seatNo;
        $data['updatetime'] = date("Y-m-d H:i:s");
        // 人脸图片是否改动
        $faceImageChange = false;
        // 闸机任务类型
        $taskType = GATE_TASK_TYPE_ADD;
        $aioTaskType = AIO_TASK_TYPE_ADD;
        // 是否更新
        $isUpdate = false;
        if($studentId) {
            // 更新操作
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if($studentInfo['face_image'] != $data['face_image']) {
                $faceImageChange = true;
                if($studentInfo['face_image'] != '') {
                    $taskType = GATE_TASK_TYPE_UPDATE;
                    $aioTaskType = AIO_TASK_TYPE_UPDATE;
                }
            }
            $this->db->update(SchoolModel::$schoolStudentTable, $data,"id='{$studentId}'");
            $isUpdate = true;
        } else {
            if($data['face_image']) {
                $faceImageChange = true;
            }
            $data['school_id'] = $this->rmxUser['school_id'];
            $data['password'] = password_hash(123456, PASSWORD_DEFAULT);
            $data['createtime'] = $data['updatetime'];
            // 默认头像
            $data['headimgurl'] = $data['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg');
            $this->db->insert(SchoolModel::$schoolStudentTable, $data);

            $studentId = $this->db->insert_id();
        }

        // 推送消息到客户端
        $this->load->library('socket');
        $classSet = implode(",", array_merge(explode(",", $classId), explode(",", $teachClass)));
        $classSet = trim($classSet, ",");
        $this->socket->update_student_list($this->rmxSchool['id'], $classSet, $studentId);
        
        if($faceImageChange) {
            // 推送消息给客户端
            $brandInfo = $this->classesModel->get_brand_info_by_class($classId);
            $this->socket->send_face_image_update($brandInfo['id'], $studentId, $data['face_image']);
            // 插入闸机任务
            $gateParams['schoolId'] = $this->rmxSchool['id'];
            $gateParams['campusId'] = $this->campusInfo['id'];
            // 过滤软删除
            $gateParams['isDelete'] = 0;
            $gateList = $this->schoolModel->get_gate_list($gateParams);
            if($gateList) {
                $insertTaskBatch = array();
                foreach($gateList as $gate) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'gate_id' => $gate['id'],
                        'device_sn' => $gate['device_sn'],
                        'user_id' => $studentId,
                        'user_name' => $data['realname'],
                        'user_face_image' => $data['face_image'],
                        'user_type' => GATE_USER_TYPE_STUDENT,
                        'task_type' => $taskType,
                        'task_state' => GATE_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
                }
            }

            // 插入一体机任务
            $this->load->model('aioModel');
            $aioParams['schoolId'] = $this->rmxSchool['id'];
            $aioParams['campusId'] = $this->campusInfo['id'];
            // 过滤软删除
            $aioParams['isDelete'] = 0;
            $aioList = $this->aioModel->get_aio_list($aioParams);
            if($aioList) {
                $insertTaskBatch = array();
                foreach($aioList as $aio) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'aio_id' => $aio['id'],
                        'facesluice_id' => $aio['facesluice_id'],
                        'user_id' => $studentId,
                        'user_name' => $data['realname'],
                        'user_face_image' => $data['face_image'],
                        'user_type' => AIO_USER_TYPE_STUDENT,
                        'task_type' => $aioTaskType,
                        'task_state' => AIO_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
                }
            }
        }

        // 插入日志
        $this->load->library('logger');
        $actionName = $isUpdate ? 'update' : 'add';
        $actionChineseName = $isUpdate ? '修改' : '增加';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => $actionChineseName . '学生，学生id：' . $studentId . '，学生名称：' . $studentName
        ));

        // 返回值
        exit(json($msg, true));
    }
    // 重置学生登录密码
    public function reset_student_password(){
        $this->load->model('accountModel');
        $userId = $this->get("id");
        // 修改密码
        $save['password'] = password_hash(123456, PASSWORD_DEFAULT);
        $this->db->update(AccountModel::$schoolStudentTable, $save,"id='{$userId}'");

        exit(json("重置登录密码成功", true));
    }
     // 获取学生列表
    public function get_student_list(){
        $this->load->model('wxUserModel');
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        // 绑定人有无筛选
        if($this->get("bind")) $totalParams['bind'] = $data['bind'] = $this->get("bind");
        // 人脸图片有无筛选
        if($this->get("face")) {
            if($this->get("face") == 1) {
                $face = 1;
            } elseif($this->get("face") == 2) {
                $face = 0;
            }
            $totalParams['hasFaceImage'] = $data['hasFaceImage'] = $face;
        }
        // 是否过期
        if($this->get("expire")) {
            $totalParams['isExpired'] = $data['isExpired'] = $this->get("expire");
        }
                    // echo'<pre>';var_export( $this->get("expire"));exit;
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $totalParams['classId'] = $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        if($this->get("teachId")) $totalParams['teachId'] = $data['teachId'] = $this->get("teachId") ? $this->get("teachId") : 0;
        if($this->get("electiveId")) $totalParams['electiveId'] = $data['electiveId'] = $this->get("electiveId") ? $this->get("electiveId") : 0;
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $total = $this->schoolModel->get_student_list_join_bind($totalParams);
        // $total = $this->schoolModel->get_student_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        // $data['orderBy'] = '`id` DESC';
        $data['orderBy'] = '`updatetime` DESC';
        $studentList = $this->schoolModel->get_student_list_join_bind($data);
        // $studentList = $this->schoolModel->get_student_list($data);
        // 获取微信用户列表
        $wxUserList = $this->wxUserModel->get_wx_user_list();
        // 使用id作为键值
        $wxUserList = array_value_to_key($wxUserList, 'id');

        // 获取学生其他信息
        foreach($studentList as &$student) {
            $classInfo = $this->classesModel->get_class_info($student['class_id']);
            $student['className'] = $classInfo['class_name'] ? $classInfo['class_name'] : '';
            // 获取教学班
            $teachParams['classId'] = $student['teaching_class_id'] ? $student['teaching_class_id'] : 0;
            $student['teachClass'] = $this->classesModel->get_class_list($teachParams);
            // $student['teachName'] = $this->classesModel->get_teaching_class_name($student['teaching_class_id']);
            // 获取选修班
            $electiveParams['classId'] = $student['elective_class_id'] ? $student['elective_class_id'] : 0;
            $student['electiveClass'] = $this->classesModel->get_class_list($electiveParams);
            // 判断当前用户有没编辑权限
            $student['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && !in_array($student['class_id'], $this->rmxUser['classIdArr'])) {
                $student['role_change'] = false;
            }
            // 获取微信绑定人列表
            $bindParams['isDelete'] = 0;
            $bindParams['bindUserId'] = $student['id'];
            $bindParams['bindUserType'] = BIND_TYPE_STUDENT;
            $bindUserList = $this->wxUserModel->get_bind_user_list($bindParams);

            if($bindUserList) {
                $nicknameArr = array();
                foreach($bindUserList as $bindUser) {
                    if(isset($wxUserList[$bindUser['wx_user_id']])) {
                        $nickname = $wxUserList[$bindUser['wx_user_id']]['nickname'];
                        if($nickname) {
                            array_push($nicknameArr, urldecode($nickname));
                        }
                    }
                }
                $student['bindUsers'] = implode('，&nbsp;', $nicknameArr);
            } else {
                $student['bindUsers'] = '';
            }

            $bindHtmlArr = array();
            if($bindUserList) {
                $bindArr = array();
                foreach($bindUserList as $bindUser) {
                    if(isset($wxUserList[$bindUser['wx_user_id']])) {
                        $nickname = $wxUserList[$bindUser['wx_user_id']]['nickname'];
                        if($nickname) {
                            array_push($bindArr, array(
                                'id' => $bindUser['id'],
                                'nickname' => urldecode($nickname)
                            ));

                            $bindHtmlArr[] = '<a href="javascript:;" class="unbind" data-id="' . $bindUser['id'] . '" >' . urldecode($nickname) . '</a>';
                        }
                    }
                }
            }

            if($bindHtmlArr) {
                $student['bindUsers'] = implode('&nbsp;&nbsp;&nbsp;&nbsp;', $bindHtmlArr);
            } else {
                $student['bindUsers'] = '';
            }

             // 是否即将过期
             if($student['expire_date']) {
                if($student['expire_date'] > date('Y-m-d', strtotime('+7 days'))) {
                    $student['expiredSoon'] = false;
                } else {
                    $student['expiredSoon'] = true;
                }
            } else {
                $student['expiredSoon'] = true;
            }

            // 有效时间
            if($student['expire_date']) {
                if($student['expire_date'] > date('Y-m-d')) {
                    $student['expire_date'] = '<span class="text-success">' . $student['expire_date'] . '</span>';
                    $student['is_expire'] = false;
                } else {
                    // 已过期
                    $student['expire_date'] = '<span class="text-danger">' . $student['expire_date'] . '</span>';  
                    $student['is_expire'] = true;
                }
            } else {
                 // 已过期
                $student['is_expire'] = true;
            }
            // echo'<pre>';var_export($bindHtmlArr);exit;
        }

        // 返回值
        exit(admin_table_data($total, $studentList));
    }
    // 导出学生数据
    public function export_student() {
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $data['keyword'] = trim($this->get("keyword"));
        // 绑定人有无筛选
        if($this->get("bind")) $totalParams['bind'] = $data['bind'] = $this->get("bind");
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        if($this->get("teachId")) $data['teachId'] = $this->get("teachId") ? $this->get("teachId") : 0;
        if($this->get("electiveId")) $data['electiveId'] = $this->get("electiveId") ? $this->get("electiveId") : 0;

        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        $data['orderBy'] = '`id` ASC';
        $studentList = $this->schoolModel->get_student_list_join_bind($data);
        $exportData = array();
        // var_export($this->rmxSchool['expire_date']);exit;
        $firstRow = array(
            '学生名称',
            '就读班级',
            '教学班',
            '联系电话',
            '学号',
            '性别',
            '物理卡号',
            '职务',
            '座位号'
        );
        if($this->rmxSchool['expire_date']) {
            // 设置了过期时间的学校，导学生过期时间
            $firstRow[] = '有效时间';
        }
        $exportData[] = $firstRow;
        // 获取全校班级
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取学生其他信息
        foreach($studentList as &$student) {
            $student['className'] = isset($classList[$student['class_id']]) ? $classList[$student['class_id']]['class_name'] : '';
            // 获取教学班
            $teachParams['classId'] = $student['teaching_class_id'] ? $student['teaching_class_id'] : 0;
            $student['teachClass'] = $this->classesModel->get_class_list($teachParams);
            $student['teachClassNameArr'] = array();
            foreach($student['teachClass'] as $item) {
                array_push($student['teachClassNameArr'], $item['class_name']);
            }
            $student['teachClassName'] = implode(',', $student['teachClassNameArr']);
            $arr = array(
                $student['realname'],
                $student['className'],
                $student['teachClassName'],
                $student['mobile'],
                $student['username'],
                $student['gender'],
                $student['realcard'] . '',
                $student['job'],
                $student['seat_no']
            );
            if($this->rmxSchool['expire_date']) {
                // 设置了过期时间的学校，导学生过期时间
                $arr[] = $student['expire_date'];
            }
            $exportData[] = $arr;
        }
        $widthParams = array(
            array(
                'index' => 'B',
                'width' => 20
            ),
            array(
                'index' => 'C',
                'width' => 20
            ),
            array(
                'index' => 'D',
                'width' => 16
            ),
            array(
                'index' => 'E',
                'width' => 20
            ),
            array(
                'index' => 'G',
                'width' => 20
            ),
            array(
                'index' => 'J',
                'width' => 20
            )
        );
        exportExcel('学生数据表', $exportData, $widthParams);
    }
    // 导出物理卡号数据
    public function export_student_realcard() {
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $data['keyword'] = trim($this->get("keyword"));
        // 绑定人有无筛选
        if($this->get("bind")) $totalParams['bind'] = $data['bind'] = $this->get("bind");
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        if($this->get("teachId")) $data['teachId'] = $this->get("teachId") ? $this->get("teachId") : 0;
        if($this->get("electiveId")) $data['electiveId'] = $this->get("electiveId") ? $this->get("electiveId") : 0;

        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        $data['orderBy'] = '`id` ASC';
        $studentList = $this->schoolModel->get_student_list_join_bind($data);
        $exportData = array();
        // echo '<pre>';var_export($studentList);exit;
        $firstRow = array(
            '学生名称',
            '就读班级',
            '学号',
            '物理卡号'
        );
        $exportData[] = $firstRow;
        // 获取全校班级
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取学生其他信息
        foreach($studentList as &$student) {
            $student['className'] = isset($classList[$student['class_id']]) ? $classList[$student['class_id']]['class_name'] : '';
            $arr = array(
                $student['realname'],
                $student['className'],
                $student['username'],
                $student['realcard'] . ''
            );
            $exportData[] = $arr;
        }
        $widthParams = array(
            array(
                'index' => 'B',
                'width' => 16
            ),
            array(
                'index' => 'C',
                'width' => 20
            ),
            array(
                'index' => 'D',
                'width' => 24
            )
        );
        exportExcel('学生物理卡号数据表', $exportData, $widthParams);
    }

    // 删除学生
    public function delete_student_action() {
        $id = $this->post('id');
        $studentInfo = $this->schoolModel->get_student_info($id);

        $data = array(
            'is_delete' => 1,
            'face_image' => '',
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(SchoolModel::$schoolStudentTable, $data, array('id' => $id));

        if($studentInfo['face_image']) {
            // 插入闸机任务
            $gateParams['schoolId'] = $this->rmxSchool['id'];
            $gateParams['campusId'] = $this->campusInfo['id'];
            // 过滤软删除
            $gateParams['isDelete'] = 0;
            $gateList = $this->schoolModel->get_gate_list($gateParams);
            if($gateList) {
                $insertTaskBatch = array();
                foreach($gateList as $gate) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'gate_id' => $gate['id'],
                        'device_sn' => $gate['device_sn'],
                        'user_id' => $id,
                        'user_name' => $studentInfo['realname'],
                        'user_face_image' => $studentInfo['face_image'],
                        'user_type' => GATE_USER_TYPE_STUDENT,
                        'task_type' => GATE_TASK_TYPE_DELETE,
                        'task_state' => GATE_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
                }
            }

            // 插入一体机任务
            $this->load->model('aioModel');
            $aioParams['schoolId'] = $this->rmxSchool['id'];
            $aioParams['campusId'] = $this->campusInfo['id'];
            // 过滤软删除
            $aioParams['isDelete'] = 0;
            $aioList = $this->aioModel->get_aio_list($aioParams);
            if($aioList) {
                $insertTaskBatch = array();
                foreach($aioList as $aio) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'aio_id' => $aio['id'],
                        'facesluice_id' => $aio['facesluice_id'],
                        'user_id' => $id,
                        'user_name' => $studentInfo['realname'],
                        'user_face_image' => $studentInfo['face_image'],
                        'user_type' => AIO_USER_TYPE_STUDENT,
                        'task_type' => AIO_TASK_TYPE_DELETE,
                        'task_state' => AIO_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
                }
            }
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('delete');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '删除学生，学生id：' . $id . '，学生名称：' . $studentInfo['realname']
        ));

        exit(json('删除成功', true));
    }
    // 解绑学生卡号
    public function unbind_action(){
        $this->load->model('wxUserModel');
        $id = $this->get("id");
        // 修改密码
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(WxUserModel::$wxUserBindTable, $data, "id='{$id}'");

        exit(json("解绑成功", true));
    }
   
    // 学校课程管理
    public function lesson(){
        // 判断是否已存在科目数据
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->schoolModel->get_lesson_list($totalParams);
        if($total > 0) {
            $this->existSubjectData = true;
        } else {
            $this->existSubjectData = false;
        }

        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "lesson");
    }
    // 导出科目数据
    public function export_subject_data() {
        $exportData = array();
        $firstRow = array(
            '科目名称'
        );
        $exportData[] = $firstRow;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $params['isDelete'] = 0;
        $subjectList = $this->schoolModel->get_lesson_list($params);
        foreach($subjectList as $item) {
            $arr = array(
                $item['lesson_name']
            );
            $exportData[] = $arr;
        }
        $widthParams = array(
            array(
                'index' => 'A',
                'width' => 30
            )
        );
        exportExcel('科目数据表', $exportData, $widthParams);
    }

    public function save_lesson_action(){
        $lessonId = $this->post("id");
        $lessonName = trim($this->post("lesson_name"));
        $lessonMode = $this->post("lesson_mode") ? trim($this->post("lesson_mode")) : '';
        $lessonImg = $this->post("lesson_img") ? $this->post("lesson_img") : '';
        // 数据检查
        if(!$lessonName) throw new Exception("请填写课程名称");
        // 判断是否已存在课程名称
        if($this->schoolModel->check_subject_name_exists($this->rmxSchool['id'], $lessonName, $lessonId)) {
            throw new Exception("课程名称已存在");
        }
        // 入库
        $data['lesson_name'] = $lessonName;
        $data['lesson_mode'] = $lessonMode;
        $data['lesson_img'] = $lessonImg;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($lessonId) {
             $this->db->update(schoolModel::$schoolLessonTable, $data,"id='{$lessonId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(schoolModel::$schoolLessonTable, $data);
            $insertId = $this->db->insert_id();
        }
        $msg = $lessonId ? '修改课程成功' : '添加课程成功';

        // 插入日志
        $this->load->library('logger');
        $actionName = $lessonId ? 'update' : 'add';
        $actionChineseName = $lessonId ? '修改' : '增加';
        $actionType = $this->logger->get_action_type($actionName);
        $id = $lessonId ? $lessonId : $insertId;
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => $actionChineseName . '科目，科目id：' . $id . '，科目名称：' . $lessonName
        ));

        exit(json($msg, true));
    }
    // 获取学校课程
    public function get_lesson_list(){
        // 筛选
        if($this->get("keyword")) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->schoolModel->get_lesson_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        $gradeList = $this->schoolModel->get_lesson_list($data);
        // 返回值
        exit(admin_table_data($total, $gradeList));
    }
    // 删除科目
    public function delete_lesson_action() {
        $id = $this->post('id');
        $subjectInfo = $this->schoolModel->get_lesson_info($id);
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(SchoolModel::$schoolLessonTable, $data, array('id' => $id));
        // 删除对应科目名称的课程
        $this->db->update(ClassesModel::$scheduleLessonTable, $data, array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'schedule_lesson' => $subjectInfo['lesson_name'],
            'is_delete' => 0
        ));
        // 删除对应科目id的考场exam_room
        $this->db->update(DataModel::$examRoomTable, $data, array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'lesson_id' => $subjectInfo['id'],
            'is_delete' => 0
        ));

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('delete');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '删除科目，科目id：' . $id . '，科目名称：' . $subjectInfo['lesson_name']
        ));
  

        exit(json('删除成功', true));
    }

    // 根据年级id，获取班级列表
    public function get_class_list($gradeId){
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['gradeId'] = $gradeId ? $gradeId : -1;
        $params['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($params);

        exit(json("", true, $classList));
    }

    //获取首页统计数据
    private function _get_index_data(){
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getRowNumber'] = true;
        $params['isDelete'] = 0;
        // 获取教师人数
        $data['teacherNum'] = $this->schoolModel->get_teacher_list($params);
        // 获取学生人数
        $data['studentNum'] = $this->schoolModel->get_student_list($params);
        // 获取课室数量
        $data['classroomNum'] = $this->classesModel->get_classroom_list($params);
        //获取在线班牌数量
        $data['brandOnlineNum'] = $this->classesModel->get_brand_list(array_merge(['online' => 1], $params));
        //获取离线班牌数量
        $data['brandOfflineNum'] = $this->classesModel->get_brand_list(array_merge(['online' => 0], $params));
        //获取当日人数统计
        $data['dateStudentNum'] = $this->_get_date_student_num(array_merge(['date' => date('Y-m-d')], $params));
        //获取7天的作业量统计    
        $data['dataNum'] = $this->_get_work_data_num($params);
        return $data;
    }

    //获取当日人数统计
    public function get_date_student_num($date){
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getRowNumber'] = true;
        $params['isDelete'] = 0;
        $params = array_merge($params, array('date' => $date));
        $data = $this->_get_date_student_num($params);
        exit(json("", true, $data));
    }

    //获取7天的作业量统计
    public function get_work_data_num($beginDate, $endDate) {
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getRowNumber'] = true;
        $params['isDelete'] = 0;
        $params = array_merge($params, array('range_date' => array($beginDate, $endDate)));
        $data = $this->_get_work_data_num($params);
        exit(json("", true, $data));
    }

    //私有方法，获取当日人数统计
    private function _get_date_student_num($params=array()){
        $data= array();
        //获取学校所有人数
        $data['studentNum'] = $this->schoolModel->get_student_list($params);
        //获取今天已到人数
        // $data['dateSignNum'] = $this->dataModel->get_date_sign_count($params);
        // $signData = $this->dataModel->get_school_sign_data($params['date'], $params['schoolId'], $params['campusId']);
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->rmxSchool['id'];
        $schduleParams['campusId'] = $this->campusInfo['id'];
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        // 之前日期的考勤按最后一节情况
        $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $params['date']);
        // foreach($signData as &$item) {
        //     if($item['sign_id']) {
        //         if($item['state'] == SIGN_STATE_LEAVE) {
        //             // 离校
        //             $item['sign_id'] = 0;
        //         } else {
        //             if($item['schedule_class_index'] < $refreshClassIndex) {
        //                 // 重新签到后还没签
        //                 $item['sign_id'] = 0;
        //             }
        //         }
        //     }
        // }
        // $data['dateSignNum'] = 0;
        // // 计算签到个数
        // foreach($signData as $item2) {
        //     if($item2['sign_id']) {
        //         $data['dateSignNum'] ++;
        //     }
        // }

        $data['dateSignNum'] = $this->dataModel->get_school_sign_data_count($params['date'], $params['schoolId'], $params['campusId'], $refreshClassIndex);
        // var_export($data['dateSignNum']);exit;
        //获取今天未到人数
        $data['dateNotSignNum'] = $data['studentNum'] - $data['dateSignNum'];
        if ($data['dateNotSignNum'] < 0) {
            $data['dateNotSignNum'] = 0;
        }
        //获取今天考勤人数,暂时为0
        $data['dateAttendNum'] = 0;
        //获取今天请假人数,暂时为0
        $data['dateLeaveNum'] = 0;
        return $data;
    }

    //私有方法，获取某段时间内的作业量统计
    private function _get_work_data_num($params=array()){
        $data= array();
        //获取某段时间内作业量
        $data['homeworkNum'] = $this->dataModel->get_homework_count($params);
        //获取某段时间内动态量
        $data['newsNum'] = $this->dataModel->get_news_count($params);
        //获取某段时间内通知量
        $data['notifyNum'] = $this->dataModel->get_notify_count($params);
        //获取某段时间内紧急公告量
        $data['urgentNotifyNum'] = $this->dataModel->get_urgent_notify_count($params);
        //获取某段时间内校园量
        $data['announceNum'] = $this->dataModel->get_announce_count($params);
        return $data;
    }
    // 编辑/修改教师
    public function update_teacher_role(){
        $teacherIdArr = $this->post('id_arr');
        $roleArr = $this->post('role_arr');
        if(empty($teacherIdArr) || count($teacherIdArr) === 0){
            throw new Exception("请先勾选要更新的教师");
        }
        $teacherIdArr = array_unique($teacherIdArr);
        if(empty($roleArr)){
            $role = '';
        }else {         
            sort($roleArr);
            $role = implode(',', $roleArr);
        }
        $data = array();
        foreach($teacherIdArr as $id){
            $data[] = array(
                'id' => $id,
                'role_id_set' => $role
            );
        }
        $this->db->update_batch(SchoolModel::$schoolUserTable, $data, 'id');
        exit(json('更新成功', true));
    }
    // 批量删除教师
    public function delete_teacher_batch(){
        $teacherIdArr = $this->post('id_arr');
        if(empty($teacherIdArr) || count($teacherIdArr) === 0){
            throw new Exception("请先勾选要删除的教师");
        }
        $teacherIdArr = array_unique($teacherIdArr);
        $data = array();
        foreach($teacherIdArr as $id){
            $data[] = array(
                'id' => $id,
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(SchoolModel::$schoolUserTable, $data, 'id');

        // 插入日志
        $this->load->library('logger');
        $actionName = 'delete';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量删除教师，个数：' . count($teacherIdArr)
        ));

        exit(json('删除成功', true));
    }
    // 批量删除学生
    public function delete_student_batch(){
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要删除的学生");
        }
        $idArr = array_unique($idArr);
        $data = array();
        foreach($idArr as $id){
            $data[] = array(
                'id' => $id,
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(SchoolModel::$schoolStudentTable, $data, 'id');

        // 插入日志
        $this->load->library('logger');
        $actionName = 'delete';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量删除学生，个数：' . count($idArr)
        ));

        exit(json('删除成功', true));
    }
    // 批量删除科目
    public function delete_subject_batch(){
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要删除的科目");
        }
        $idArr = array_unique($idArr);
        $data = array();
        foreach($idArr as $id){
            $data[] = array(
                'id' => $id,
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(SchoolModel::$schoolLessonTable, $data, 'id');

        // 插入日志
        $this->load->library('logger');
        $actionName = 'delete';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量删除科目，个数：' . count($idArr)
        ));

        exit(json('删除成功', true));
    }
    // 批量删除课室
    public function delete_classroom_batch(){
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要删除的课室");
        }
        $idArr = array_unique($idArr);
        $data = array();
        foreach($idArr as $id){
            $data[] = array(
                'id' => $id,
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(ClassesModel::$classroomTable, $data, 'id');

        // 插入日志
        $this->load->library('logger');
        $actionName = 'delete';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量删除课室，个数：' . count($idArr)
        ));

        exit(json('删除成功', true));
    }

    // 批量导入学生卡号
    public function import_realcard() {
        // $CI =& get_instance();
        $this->load->library('PHPExcel');
        $fileLink = $this->post('fileLink');
        // 暂时只支持xls
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($fileLink);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }
        }
        if(empty($excelData)) {
            throw new Exception('该文件是空文件');
        }
        // 获取学工号和卡号的下标
        $realnameIndex = -1;
        $usernameIndex = -1;
        $readcardIndex = -1;
        foreach($excelData[1] as $key => $val) {
            if(strstr($val, '学生名称')) {
                $realnameIndex = $key;
            }
            if(strstr($val, '学工号') || strstr($val, '学号')) {
                $usernameIndex = $key;
            }
            if(strstr($val, '卡号')) {
                $readcardIndex = $key;
            }
        }
        if($realnameIndex == -1 || $usernameIndex == -1 || $readcardIndex == -1) {
            throw new Exception('表格格式错误');
        }

        // 去掉首行
        if($excelData[1][0] == '学生名称') {
            array_shift($excelData);
        } else {
            throw new Exception('表格格式错误');
        }

        // 判断卡号或学号是否重复
        $usernameArr = array();
        $realcardArr = array();
        // 获取同步数组
        $importDataArr = array();
        foreach($excelData as $data) {
            $username = trim($data[$usernameIndex]);
            $realcard = trim($data[$readcardIndex]); 
            if(in_array($username, $usernameArr)) {
                throw new Exception('学号不能重复：' . $username);
            } else {
                array_push($usernameArr, $username);
            }
            if(in_array($realcard, $realcardArr)) {
                throw new Exception('卡号不能重复：' . $realcard);
            } else {
                array_push($realcardArr, $realcard);
            }
            array_push($importDataArr, array(
                'username' => $username,
                'realcard' => $realcard,
                'updatetime' => date('Y-m-d H:i:s')
            ));
        }
        if(empty($importDataArr)) {
            throw new Exception('空数据');
        }
        
        // echo '<pre>';var_export($importDataArr);exit;
        // 获取本校全部学生
        $studentParams['schoolId'] = $this->rmxSchool['id'];
        $studentParams['campusId'] = $this->campusInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'username');
        // 计算更新多少条数据
        $updateCount = 0;
        // 过滤同步数组
        foreach($importDataArr as &$importData) {
            $username = $importData['username'];
            if(isset($studentList[$username])) {
                $importData['id'] = $studentList[$username]['id'];
                if($importData['realcard'] != $studentList[$username]['realcard']) {
                    $updateCount ++;
                }
            } else {
                throw new Exception('学号：' . $username . ' 不存在');
            }
        }
        $this->db->update_batch(SchoolModel::$schoolStudentTable, $importDataArr, 'id');
        exit(json('导入成功，更新了' . $updateCount . '条数据', true));
    }

    // 选择年级插件数据源
    public function select_grade_plugin_data_source() {
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
		// 过滤已毕业年级
        $gradeParams['excludeGraduated'] = 1;
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 数据源定义
        $gradeArr = array();
        foreach($gradeList as $grade) {
            $gradeId = $grade['id'];
            $tree['text'] = $grade['grade_name'];
            $tree['type'] = 'folder';
            $tree['attr'] = array("id" => $gradeId);

            $grade['additionalParameters']['children'] = array();
            $gradeArr["label_". $gradeId] = $tree;

            // 获取该年级对应的行政班级列表
            $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
            $gradeParams['gradeId'] = $grade['id'];
            $classArray = $this->classesModel->get_class_list($gradeParams);
            foreach($classArray as $class) {
                $tree['text'] = $class['class_name'];
                $tree['type'] = 'item';
                $tree['attr'] = array("id" => $class['id']);
                // 年级
                $gradeArr["label_". $gradeId]['additionalParameters']['children'][] = $tree;
            }
        }
        exit(json('', true, $gradeArr));
    }

    // 选择默认年级插件数据源
    public function select_default_grade_plugin_data_source() {
        // 获取学段列表
        $periodList = $this->classesModel->get_grade_period_list();
        // 数据源定义
        $defaultGradeArr = array();
        foreach($periodList as $period) {
            $periodId = $period['id'];
            $tree['text'] = $period['name'];
            $tree['type'] = 'folder';
            $tree['attr'] = array("id" => $periodId);
            $period['additionalParameters']['children'] = array();
            $defaultGradeArr["label_". $periodId] = $tree;
            // 获取该学段对应的默认年级列表
            $defaultGradeParams['periodId'] = $periodId;
            $defaultGradeParams['excludeGraduated'] = 1;
            $list = $this->classesModel->get_default_grade_list($defaultGradeParams);
            foreach($list as $item) {
                $tree['text'] = $item['name'];
                $tree['type'] = 'item';
                $tree['attr'] = array("id" => $item['id']);
                // 默认年级
                $defaultGradeArr["label_". $periodId]['additionalParameters']['children'][] = $tree;
            }
        }
        exit(json('', true, $defaultGradeArr));
    }

    // 批量更新学生班级
    public function batch_update_student_class() {
        $classId = $this->post('class_id');
        $studentIdArr = $this->post('id_arr');
        if(empty($studentIdArr) || count($studentIdArr) === 0) {
            throw new Exception("请先勾选要更新的学生");
        }
        $studentIdArr = array_unique($studentIdArr);
        $data = array();
        foreach($studentIdArr as $id){
            $data[] = array(
                'id' => $id,
                'class_id' => $classId
            );
        }
        $this->db->update_batch(SchoolModel::$schoolStudentTable, $data, 'id');
        exit(json('更新成功', true));
    }

    // 健康信息页面
    public function health(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);
        // 获取年级对应的教学班级列表
        $gradeParams['classType'] = CLASSES_TYPE_TEACHING;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeTeachingClassList = json_encode($classArray);

        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);
        // 获取教学班
        $classParams['classType'] = CLASSES_TYPE_TEACHING;
        $this->teachingClassList = $this->classesModel->get_class_list($classParams);
        // 获取选修班
        $classParams['classType'] = CLASSES_TYPE_ELECTIVE;
        $this->electiveClassList = $this->classesModel->get_class_list($classParams);
        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->healthData = get_health_const_data();
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "health");
    }

     // 获取健康列表
     public function get_health_list(){
        $this->load->model('wxUserModel');
        // 用户名称筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        // var_export($this->get("treatment"));exit;
        // 学生班级筛选
        if($this->get("class_id") !== NULL && $this->get("class_id") !== '') $totalParams['classId'] = $data['classId'] = $this->get("class_id") ? $this->get("class_id") : 0;
        if($this->get("bindusertype") !== NULL && $this->get("bindusertype") !== '') $totalParams['bindusertype'] = $data['bindusertype'] = $this->get("bindusertype");
        if($this->get("is_contact") !== NULL && $this->get("is_contact") !== '') $totalParams['is_contact'] = $data['is_contact'] = $this->get("is_contact");
        if($this->get("is_return") !== NULL && $this->get("is_return") !== '') $totalParams['is_return'] = $data['is_return'] = $this->get("is_return");
        if($this->get("is_detained") !== NULL && $this->get("is_detained") !== '') $totalParams['is_detained'] = $data['is_detained'] = $this->get("is_detained");
        if($this->get("current_status") !== NULL && $this->get("current_status") !== '') $totalParams['current_status'] = $data['current_status'] = $this->get("current_status");
        if($this->get("family_status") !== NULL && $this->get("family_status") !== '') $totalParams['family_status'] = $data['family_status'] = $this->get("family_status");
        if($this->get("treatment") !== NULL && $this->get("treatment") !== '') $totalParams['treatment'] = $data['treatment'] = $this->get("treatment");
        if($this->get("symptom") !== NULL && $this->get("symptom") !== '') $totalParams['symptom'] = $data['symptom'] = $this->get("symptom");
        if($this->get("begin_time") !== NULL && $this->get("begin_time") !== '') $totalParams['begin_time'] = $data['begin_time'] = $this->get("begin_time");
        if($this->get("end_time") !== NULL && $this->get("end_time") !== '') $totalParams['end_time'] = $data['end_time'] = $this->get("end_time");
        if($this->get("createdate") !== NULL && $this->get("createdate") !== '') $totalParams['createdate'] = $data['createdate'] = $this->get("createdate");
        // 学生年级筛选
        if(empty($this->get("class_id")) && $this->get("grade_id")) {
            $params['gradeId'] = $this->get("grade_id");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }
        // var_export($totalParams);

        $total = $this->wxUserModel->get_wx_user_health_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        // 按id倒序
        $data['orderBy'] = '`createtime` DESC';
        $healthList = $this->wxUserModel->get_wx_user_health_list($data);
        // 获取其他信息
        $healthData = get_health_const_data();
        foreach($healthList as &$health) {
            $health['bindUserType'] = $health['bind_user_type'] == BIND_TYPE_STUDENT ? '学生' :'教师';
            $health['current_status'] = $healthData['current_status'][$health['current_status']];
            $health['family_status'] = $healthData['family_status'][$health['family_status']];
            $health['treatment'] = $healthData['treatment'][$health['treatment']];
            $health['is_return'] = $health['is_return'] ? '是' : '否';
            $health['is_contact'] = $health['is_contact'] ? '是' : '否';
            $health['is_detained'] = $health['is_detained'] ? '是' : '否';
             // 获取症状数组
             $symptomkeyArr = explode(',', $health['symptom']);
             // 获取症状字符数组
             $symptomArr = array();
             if($symptomkeyArr) {
                 foreach($symptomkeyArr as $symptomkey) {
                     if($symptomkey) {
                        array_push($symptomArr, $healthData['symptom'][$symptomkey]);
                     }
                 }
                 $health['symptom'] = implode(',', $symptomArr);
             }
            $health['symptom'] = $health['symptom'] ? $health['symptom'] :'自觉正常';  
         }

        // 返回值
        exit(admin_table_data($total, $healthList));
    }

     // 导出健康表格
     public function export_health(){
        $this->load->model('wxUserModel');
        // 用户名称筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        // var_export($this->get("treatment"));exit;
        // 学生班级筛选
        if($this->get("class_id")) $data['classId'] = $this->get("class_id") ? $this->get("class_id") : 0;
        if($this->get("bindusertype") !== NULL && $this->get("bindusertype") !== '') $data['bindusertype'] = $this->get("bindusertype");
        if($this->get("is_contact") !== NULL && $this->get("is_contact") !== '') $data['is_contact'] = $this->get("is_contact");
        if($this->get("is_return") !== NULL && $this->get("is_return") !== '') $data['is_return'] = $this->get("is_return");
        if($this->get("is_detained") !== NULL && $this->get("is_detained") !== '') $data['is_detained'] = $this->get("is_detained");
        if($this->get("current_status") !== NULL && $this->get("current_status") !== '') $data['current_status'] = $this->get("current_status");
        if($this->get("family_status") !== NULL && $this->get("family_status") !== '') $data['family_status'] = $this->get("family_status");
        if($this->get("treatment") !== NULL && $this->get("treatment") !== '')  $data['treatment'] = $this->get("treatment");
        if($this->get("symptom") !== NULL && $this->get("symptom") !== '')  $data['symptom'] = $this->get("symptom");
        if($this->get("begin_time") !== NULL && $this->get("begin_time") !== '')  $data['begin_time'] = $this->get("begin_time");
        if($this->get("end_time") !== NULL && $this->get("end_time") !== '') $data['end_time'] = $this->get("end_time");
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }
        // var_export($totalParams);
        // 获取数据
        // $data['pageStart'] = $this->get('start');
        // $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        // 按id倒序
        $data['orderBy'] = '`createtime` DESC';
        $healthList = $this->wxUserModel->get_wx_user_health_list($data);
        // if(empty($healthList)) {
        //     throw new Exception('当前无数据');
        // }
        // 获取其他信息
        $healthData = get_health_const_data();
        foreach($healthList as &$health) {
            $health['bindUserType'] = $health['bind_user_type'] == BIND_TYPE_STUDENT ? '学生' :'教师';
            $health['current_status'] = $healthData['current_status'][$health['current_status']];
            $health['family_status'] = $healthData['family_status'][$health['family_status']];
            $health['treatment'] = $healthData['treatment'][$health['treatment']];
            $health['is_return'] = $health['is_return'] ? '是' : '否';
            $health['is_contact'] = $health['is_contact'] ? '是' : '否';
            $health['is_detained'] = $health['is_detained'] ? '是' : '否';
             // 获取症状数组
             $symptomkeyArr = explode(',', $health['symptom']);
             // 获取症状字符数组
             $symptomArr = array();
             if($symptomkeyArr) {
                 foreach($symptomkeyArr as $symptomkey) {
                     if($symptomkey) {
                        array_push($symptomArr, $healthData['symptom'][$symptomkey]);
                     }
                 }
                 $health['symptom'] = implode(',', $symptomArr);
             }
            $health['symptom'] = $health['symptom'] ? $health['symptom'] :'自觉正常';  
         }
         $data = array (
            array (
                '序号',
                '用户名称',
                '角色',
                '就读/任课班级',
                '目前状态',
                '家属状态',
                '诊疗情况',
                '症状',
                '是否密切接触',
                '往返武汉及毗邻地区',
                '是否滞留在湖北地区',
                '假期去向',
                '详细地址',
                '用户手机',
                '创建时间',
        ));
        foreach($healthList as $key => $item) {
            $arr = array(
                ++$key,
                $item['realname'],
                $item['bindUserType'],
                $item['class_names'],
                $item['current_status'],
                $item['family_status'],
                $item['treatment'],
                $item['symptom'],
                $item['is_contact'],
                $item['is_return'],
                $item['is_detained'],
                $item['holiday_dest'],
                $item['holiday_dest_desc'],
                $item['mobile'],
                $item['createtime']
            );
            array_push($data, $arr);
        }
         $filename = $this->rmxSchool['school_name'] . '防疫信息' . date('YmdHis');
         exportHealthExcel($filename, $data);

        // // 返回值
        // exit(json('', true, $healthList));
    }

    // 健康预警信息页面
    public function health_warn(){

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "health_warn");
    }

    // 获取健康预警信息列表
    public function get_health_warn_list(){
        $this->load->model('wxUserModel');
        $params['schoolId'] = $this->rmxSchool['id'];
        $warnList = $this->wxUserModel->get_wx_user_health_warn_list($params);
        // var_export(($warnList));exit;
        $resultArr = array();
        $healthWarnKeyData = get_health_warn_key_const_data();
        $healthWarnData = get_health_warn_const_data();
        foreach($warnList as $warn) {
            $warnKey = $healthWarnKeyData[$warn['key']];
            $key = $warn['key'];
            $value = $warn['value'];
            $arr = explode(',', $value);
            $valueArr = array();
            foreach($arr as $item) {
                array_push($valueArr, $healthWarnData[$key][$item]);
            }
            $valueStr = implode(',', $valueArr);
            $temp = array(
                'id' => $warn['id'],
                'key' => $warnKey,
                'value' => $valueStr,
                'createtime' => $warn['createtime']
            );
            array_push($resultArr, $temp);
        }

        // var_export(($resultArr));exit;
        // $warnList = array(
        //     array(
        //         'id' => '1',
        //         'key' => '是否往返武汉及毗邻地区',
        //         'value' => '是',
        //         'createtime' => '2020-02-03 14:16:18',
        //     ),
        //     array(
        //         'id' => '2',
        //         'key' => '是否与疫情高发地人员有密切接触',
        //         'value' => '是',
        //         'createtime' => '2020-02-03 14:17:28',
        //     ),
        //     array(
        //         'id' => '3',
        //         'key' => '出现的症状',
        //         'value' => '发热、干咳、感冒、腹泻',
        //         'createtime' => '2020-02-03 14:17:56',
        //     ),
        // );
        // 返回值
        exit(admin_table_data(count($resultArr), $resultArr));
    }

    // 添加健康预警信息页面
    public function health_warn_edit($id = 0){
        $this->load->model('wxUserModel');
        $this->healthWarnKeyData = get_health_warn_key_const_data();
        $healthWarnData = get_health_warn_const_data();
        // 过滤掉症状‘自觉正常’
        foreach($healthWarnData['symptom'] as $key => $sym) {
            if($sym == '自觉正常') {
                unset($healthWarnData['symptom'][$key]);
            }
        }
        $this->healthWarnData = $healthWarnData;
        $this->healthWarnJson = json_encode($this->healthWarnData, JSON_UNESCAPED_UNICODE);
        $this->defaultKey = 'current_status';
        if($id) {
            $warnInfo = $this->wxUserModel->get_wx_user_health_warn_info($id);
            if($warnInfo) {
                $this->defaultKey = $warnInfo['key'];
                // $warnInfo['']
                $warnInfo['valueArr'] = explode(',', $warnInfo['value']);
                $this->warnInfo = $warnInfo;
            }
        }
        $warnInfo = array();
        if($warnInfo) {
            $this->defaultKey = $warnInfo['key'];
        }
        // var_export(($resultArr));exit;

        $this->studentInfo = array();
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "health_warn_edit");
    }

    // 保存预警字段
    public function save_health_warn_action() {
        $this->load->model('wxUserModel');
        $id = $this->post('id');
        $key = $this->post('key');
        $valueArr = $this->post('value');
        // var_export($value);exit;
        if(empty($key)) {
            throw new Exception('预警字段不能为空');
        }
        if(empty($valueArr)) {
            throw new Exception('预警值不能为空');
        }
        // 判断是否已经添加过该字段
        if(empty($id)) {
            $warnInfo = $this->wxUserModel->get_wx_user_health_warn_info_by_key($this->rmxSchool['id'], $key);
            if($warnInfo) {
                throw new Exception('该字段已添加过');
            }
        }
        $value = implode(',', $valueArr);
        $data['key'] = $key;
        $data['value'] = $value;
        $data['is_delete'] = 0;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($id) {
            $this->db->update(WxUserModel::$wxUserHealthWarnTable, $data, "id='{$id}'");
        } else {
            $data['school_id'] = $this->rmxUser['school_id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(WxUserModel::$wxUserHealthWarnTable, $data);
        }
        $msg = $id ? '修改成功' : '添加成功';
        exit(json($msg, true));
    }

    // 删除预警字段
    public function delete_health_warn_action() {
        $this->load->model('wxUserModel');
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(WxUserModel::$wxUserHealthWarnTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    // 健康统计页面
    public function health_statistics(){
        $this->load->model('wxUserModel');
        $beginDate = $this->get('begindate');
        $endDate = $this->get('enddate');
        if($beginDate && $endDate) {
            // 获取日期数组
            $dateArr = getDateFromRange($beginDate, $endDate);
            $this->begindate = $beginDate;
            $this->enddate = $endDate;
        } else {
            // 默认最近14天
            $dateArr = getDateFromRange(date('Y-m-d', strtotime("-13 day")), date('Y-m-d'));
        }
        // 获取预警字段列表
        $warnDataArr = $this->wxUserModel->get_wx_user_health_warn_list(array(
            'schoolId' => $this->rmxSchool['id']
        ));
        // echo '<pre>';var_export($warnDataArr);exit;
        // 获取教师和学生总数
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['isDelete'] = 0;
        $params['getRowNumber'] = 1;
        $studentNum = $this->schoolModel->get_student_list($params);
        $teacherNum = $this->schoolModel->get_teacher_list($params);
        $totalNum = $studentNum + $teacherNum;
        $committedNumArr = array();
        $unCommittedNumArr = array();
        $warnNumArr = array();
        $tableNumArr = array();
        // 获取数据
        foreach($dateArr as $date) {
            $data['schoolId'] = $this->rmxSchool['id'];
            $data['getRowNumber'] = 1;
            $data['createdate'] = $date;
            $healthNum = $this->wxUserModel->get_wx_user_health_list($data);
            // 已提交数
            $committedNumArr[$date] = $healthNum;
            $tableNumArr['committed'][] = $healthNum; 
            // 未提交数
            $unCommittedNumArr[$date] = $totalNum - $healthNum;
            $tableNumArr['unCommitted'][] = $totalNum - $healthNum;
            // 获取截止日期最近一条
            $currentData['schoolId'] = $this->rmxSchool['id'];
            $currentData['enddate'] = $date;
            $currentHealthArr = $this->wxUserModel->get_wx_user_health_list($currentData);
            $warnNum = 0;
            // 预警人数
            if($warnDataArr) {
                foreach($currentHealthArr as $health) {
                    $isWarn = false;
                    foreach($warnDataArr as $warn) {
                        $warnKey = $warn['key'];
                        $warnVal = $warn['value'];
                        $warnValArr = explode(',', $warnVal);
                        $healthVal = $health[$warnKey];
                        $healthValArr = explode(',', $healthVal);
                        foreach($healthValArr as $val) {
                            if(in_array($val, $warnValArr)) {
                                $isWarn = true;
                            }
                            continue;
                        }
                    }
                    if($isWarn) {
                        $warnNum ++;
                    }
                }
            }
            // 预警人数
            $warnNumArr[$date] = $warnNum;
            $tableNumArr['warn'][] = $warnNum; 
        }
        // $res = array(
        //     'committed' => $committedNumArr,
        //     'unCommitted' => $unCommittedNumArr,
        //     'warn' => $warnNumArr
        // );
        $this->dateJson = json_encode($dateArr, JSON_UNESCAPED_UNICODE);
        $this->committedJson = json_encode($tableNumArr['committed'], JSON_UNESCAPED_UNICODE);
        $this->unCommittedJson = json_encode($tableNumArr['unCommitted'], JSON_UNESCAPED_UNICODE);
        $this->warnJson = json_encode($tableNumArr['warn'], JSON_UNESCAPED_UNICODE);
        // echo '<pre>';var_export($res);exit;

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "health_statistics");
    }
    // 卡号激活记录
    public function charge_pay(){
        $this->load->model('wxUserModel');
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);

        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);

        // 总计
        $data['isPaid'] = 1;
        $data['schoolId'] = $this->rmxSchool['id'];
        $payList = $this->wxUserModel->get_charge_pay_list($data);
        $total = 0;
        foreach($payList as $pay) {
            $total += $pay['price'];
        }
        $this->total = $total;

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "charge_pay");
    }
    // 获取支付列表
    public function get_charge_pay_list(){
        $this->load->model('wxUserModel');
        $totalParams['isPaid'] = $data['isPaid'] = 1;
        // 签到时间区间
        if($this->get("begindate")) $totalParams['begindate'] = $data['begindate'] = $this->get("begindate") ? $this->get("begindate") : 0;
        if($this->get("enddate")) $totalParams['enddate'] = $data['enddate'] = $this->get("enddate") ? $this->get("enddate") : 0;
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $totalParams['classId'] = $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 激活途径
        if($this->get("way")) $totalParams['way'] = $data['way'] = $this->get("way") ? $this->get("way") : 0;
        // 学生id
        if(trim($this->get("keyword"))) {
            $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $total = $this->wxUserModel->get_charge_pay_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $payList = $this->wxUserModel->get_charge_pay_list($data);
        // 获取学生其他信息
        foreach($payList as &$pay) {
            if($pay['active_mode'] == CHARGE_ACTIVE_TYPE_MONTH) {
                $pay['active'] = $pay['active_month'] . '个月';
            } else {
                $pay['active'] = $pay['active_time'] . '到期';
            }
            // 支付途径
            if($pay['pay_way'] == CHARGE_WAY_WX) {
                $pay['pay_way'] = '微信支付';
            } else {
                $pay['pay_way'] = '人工支付';
            }
        }
        // echo '<pre>';var_export($payList);exit;
        // 返回值
        exit(admin_table_data($total, $payList));
    }
    // 合计缴费
    public function get_charge_pay_total(){
        $this->load->model('wxUserModel');
        $data['isPaid'] = 1;
        // 签到时间区间
        if($this->get("begindate")) $data['begindate'] = $this->get("begindate") ? $this->get("begindate") : 0;
        if($this->get("enddate")) $data['enddate'] = $this->get("enddate") ? $this->get("enddate") : 0;
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 激活途径
        if($this->get("way")) $data['way'] = $this->get("way") ? $this->get("way") : 0;
        // 学生id
        if(trim($this->get("keyword"))) {
            $data['keyword'] = trim($this->get("keyword"));
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
           $data['classSet'] = $this->rmxUser['class_ids'];
        }

        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $payList = $this->wxUserModel->get_charge_pay_list($data);
        $total = 0;
        foreach($payList as $pay) {
            $total += $pay['price'];
        }
        // echo '<pre>';var_export($payList);exit;
        // 返回值
        exit(json('', true, $total));
    }
    // 卡号人工激活
    public function charge_artificial(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);

        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);

        // 获取收费项
        $data['isDelete'] = 0;
        $data['schoolId'] = $this->rmxSchool['id'];
        $chargeList = $this->schoolModel->get_charge_list($data);
        foreach($chargeList as &$charge) {
            if($charge['active_mode'] == CHARGE_ACTIVE_TYPE_MONTH) {
                $charge['active'] = $charge['active_month'] . '个月';
            } else {
                $charge['active'] = $charge['active_time'] . '到期';
            }
        }
        $this->chargeList = $chargeList;
        // echo'<pre>';var_export($chargeList);exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "charge_artificial");
    }
    // 人工激活操作
    public function artificial_activate(){
        $this->load->model('wxUserModel');
        $studentId = $this->post('student_id');
        $chargeId = $this->post('charge_id');
        if(empty($studentId) || empty($chargeId)) {
            throw new Exception('系统错误');
        }
        $student = $this->schoolModel->get_student_info($studentId);
        $charge= $this->schoolModel->get_charge_info($chargeId);
        $effectTimeBegin = $charge['effect_time_begin'];
        $effectTimeEnd = $charge['effect_time_end'];
        // 判断收费有效时间
        if($charge['effect_mode'] == CHARGE_EFFECT_TYPE_LONG || ($effectTimeBegin <= date('m-d') && $effectTimeEnd >= date('m-d'))) {
            if($charge['active_mode'] == CHARGE_ACTIVE_TYPE_MONTH) {
                $month = $charge['active_month'];
                $expireDate = $student['expire_date'];
                if(empty($expireDate) || $expireDate < date('Y-m-d')) {
                    $expireDate = date('Y-m-d');
                }
                $activeDate = date("Y-m-d", strtotime("+" . $month . " months", strtotime($expireDate)));
            } else {
                // 日期改成自带年级了
                $activeDate = $charge['active_time'];
            }
        } else {
            throw new Exception('系统错误');
        }
        // 插入订单
        $this->db->insert(WxUserModel::$chargePayTable, array(
            'school_id' => $this->rmxSchool['id'],
            'charge_id' => $chargeId,
            'out_trade_no' => '',
            'student_id' => $studentId,
            'openid' => '',
            'price' => $charge['price'],
            'is_paid' => 1,
            'expire_date' => $activeDate,
            'createtime' => date('Y-m-d H:i:s'),
            'paytime' => date('Y-m-d H:i:s'),
            'pay_way' => CHARGE_WAY_ARTIFICIAL
        ));
        // 更新过期时间
        $this->db->update(SchoolModel::$schoolStudentTable, array(
            'expire_date' => $activeDate,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'id' => $studentId
        ));
        exit(json('激活成功', true));
    }

    // 闸机管理
    public function gate(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "gate");
    }
    public function save_gate_action(){
        $gateId = $this->post("id") ? $this->post("id") : 0;
        $deviceSn = $this->post("device_sn");
        $deviceIsExit = $this->post("device_is_exit");
        $deviceDesc = $this->post("device_desc");
        // var_export(!$deviceSn);exit;
        // 数据检查
        if(!$deviceSn) throw new Exception("请填写设备序列号");
        // 检查本校是否有重复闸机
        if($this->schoolModel->check_gate_sn_exists($this->rmxSchool['id'], $this->campusInfo['id'], $deviceSn, $gateId)) {
            throw new Exception("闸机设备序列号已存在");
        }
        // 入库
        $data['device_sn'] = $deviceSn;
        $data['device_is_exit'] = $deviceIsExit;
        $data['device_desc'] = $deviceDesc;
        if($gateId) {
            $this->db->update(SchoolModel::$gateTable, $data,"id='{$gateId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['createtime'] = date('Y-m-d H:i:s');
            $this->db->insert(SchoolModel::$gateTable, $data);
            $insertGateId = $this->db->insert_id();
            // 添加闸机任务，遍历全校区有录入人脸的学生
            $studentParams['schoolId'] = $this->rmxSchool['id'];
            $studentParams['campusId'] = $this->campusInfo['id'];
            $studentParams['isDelete'] = 0;
            $studentParams['hasFaceImage'] = 1;
            $studentList = $this->schoolModel->get_student_list($studentParams);
            $insertTaskBatch = array();
            foreach($studentList as $student) {
                array_push($insertTaskBatch, array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'gate_id' => $insertGateId,
                    'device_sn' => $deviceSn,
                    'user_id' => $student['id'],
                    'user_name' => $student['realname'],
                    'user_face_image' => $student['face_image'],
                    'user_type' => GATE_USER_TYPE_STUDENT,
                    'task_type' => GATE_TASK_TYPE_ADD,
                    'task_state' => GATE_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
            }

            // 添加闸机任务，遍历全校有录入人脸的教师
            $teacherParams['schoolId'] = $this->rmxSchool['id'];
            $teacherParams['isDelete'] = 0;
            $teacherParams['hasFaceImage'] = 1;
            $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
            $insertTeacherTaskBatch = array();
            foreach($teacherList as $teacher) {
                array_push($insertTeacherTaskBatch, array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'gate_id' => $insertGateId,
                    'device_sn' => $deviceSn,
                    'user_id' => $teacher['id'],
                    'user_name' => $teacher['realname'],
                    'user_face_image' => $teacher['face_image'],
                    'user_type' => GATE_USER_TYPE_TEACHER,
                    'task_type' => GATE_TASK_TYPE_ADD,
                    'task_state' => GATE_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTeacherTaskBatch) {
                $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTeacherTaskBatch);
            }

        }
        $msg = $gateId ? '修改闸机成功' : '添加闸机成功';
        exit(json($msg, true));
    }
    // 获取闸机列表
    public function get_gate_list(){
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->schoolModel->get_gate_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $list = $this->schoolModel->get_gate_list($data);
        foreach($list as $key => $item) {
            // 转换设备类型
            $list[$key]['isExit'] = $item['device_is_exit'] == 1 ? '出口' : '入口';
        }
        // 返回值
        exit(admin_table_data($total, $list));
    }
    // 删除闸机
    public function delete_gate_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1
        );
        $this->db->update(SchoolModel::$gateTable, $data, array('id' => $id));
        // 删除对应的任务
        $this->db->update(SchoolModel::$gateTaskTable, $data, array('gate_id' => $id));
    
        exit(json('删除成功', true));
    }
    // 闸机任务列表
    public function gate_task(){
        // 获取闸机列表
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $this->gateList = $this->schoolModel->get_gate_list($data);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "gate_task");
    }
    // 获取闸机任务列表
    public function get_gate_task_list(){
        if($this->get('gate_id')) {
            $totalParams['gateId'] = $this->get('gate_id');
            $data['gateId'] = $this->get('gate_id');
        }
        if($this->get('realname')) {
            $totalParams['realname'] = $this->get('realname');
            $data['realname'] = $this->get('realname');
        }
        if($this->get('task_type')) {
            $totalParams['taskType'] = $this->get('task_type');
            $data['taskType'] = $this->get('task_type');
        }
        if($this->get('task_state')) {
            $totalParams['taskState'] = $this->get('task_state');
            $data['taskState'] = $this->get('task_state');
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->schoolModel->get_gate_task_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $list = $this->schoolModel->get_gate_task_list($data);
        foreach($list as $key => $item) {
            // 转换设备类型
            $list[$key]['user_type_format'] = transform_gate_user_type($item['user_type']);
            $list[$key]['task_type_format'] = transform_gate_task_type($item['task_type']);
            $list[$key]['task_state_format'] = transform_gate_task_state($item['task_state']);
        }
        // 返回值
        exit(admin_table_data($total, $list));
    }

    // 学生账号管理
    public function student_account(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);


        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);
       

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "student_account");
    }

    // 获取学生列表
    public function get_student_list_for_account(){
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        // 学生姓名筛选
        // var_export($this->get("limit") );exit;
        if($this->get("limit") === '1' || $this->get("limit") === '0') $totalParams['limit'] = $data['limit'] = trim($this->get("limit"));
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $totalParams['classId'] = $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $total = $this->schoolModel->get_student_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        $data['orderBy'] = '`id` DESC';
        $studentList = $this->schoolModel->get_student_list($data);

        // 获取学生其他信息
        foreach($studentList as &$student) {
            $classInfo = $this->classesModel->get_class_info($student['class_id']);
            $student['className'] = $classInfo['class_name'] ? $classInfo['class_name'] : '';
            // 判断当前用户有没编辑权限
            $student['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && !in_array($student['class_id'], $this->rmxUser['classIdArr'])) {
                $student['role_change'] = false;
            }
            // 是否限制增值功能
            if($student['is_limit'] == 1) {
                $student['isLimitFormat'] = '<label class="text-danger">是</label>';
                // $student['isLimitFormat2'] = '<label class="text-danger">已限制</label>';
            } else {
                $student['isLimitFormat'] = '<label class="text-success">否</label>';
                // $student['isLimitFormat2'] = '<label class="text-success">未限制</label>';
            }
        }
        // echo '<pre>';var_export($studentList);exit;
        // 返回值
        exit(admin_table_data($total, $studentList));
    }

    // 设置增值功能操作
    public function update_student_limit_action() {
        $id = $this->post('id');
        $limit = $this->post('limit');
        $data = array(
            'is_limit' => $limit,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(SchoolModel::$schoolStudentTable, $data, array('id' => $id));
        $msg = $limit == 1 ? '限制增值功能成功' : '解除限制成功';
        exit(json($msg, true));
    }

    // 批量设置增值功能操作
    public function update_student_limit_batch_action() {
        $idArr = $this->post('id_arr');
        $limit = $this->post('limit');

        // var_export($idArr);exit;
        $limit = $this->post('limit');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要更新的学生");
        }
        $data = array();
        foreach($idArr as $id){
            $data[] = array(
                'id' => $id,
                'is_limit' => $limit,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(SchoolModel::$schoolStudentTable, $data, 'id');
        $msg = $limit == 1 ? '批量限制增值功能成功' : '批量解除限制成功';
        exit(json($msg, true));
    }
    // 导出激活记录数据
    public function export_charge_pay() {
        $this->load->model('wxUserModel');
        $data['isPaid'] = 1;
        // 签到时间区间
        if($this->get("begindate")) $data['begindate'] = $this->get("begindate") ? $this->get("begindate") : 0;
        if($this->get("enddate")) $data['enddate'] = $this->get("enddate") ? $this->get("enddate") : 0;
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 激活途径
        if($this->get("way")) $data['way'] = $this->get("way") ? $this->get("way") : 0;
        // 学生id
        if(trim($this->get("keyword"))) {
            $data['keyword'] = trim($this->get("keyword"));
        }
        // 获取数据条数
        $data['schoolId'] = $this->rmxSchool['id'];
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $data['schoolId'] = $this->rmxSchool['id'];
        $payList = $this->wxUserModel->get_charge_pay_list($data);
        // 获取学生其他信息
        foreach($payList as &$pay) {
            if($pay['active_mode'] == CHARGE_ACTIVE_TYPE_MONTH) {
                $pay['active'] = $pay['active_month'] . '个月';
            } else {
                $pay['active'] = $pay['active_time'] . '到期';
            }
            // 支付途径
            if($pay['pay_way'] == CHARGE_WAY_WX) {
                $pay['pay_way'] = '微信支付';
            } else {
                $pay['pay_way'] = '人工支付';
            }
        }

        $exportData = array();
        // echo'<pre>';var_export($payList);exit;
        $firstRow = array(
            '学生名称',
            '就读班级',
            '学号',
            '收费项',
            '价格（元）',
            '激活方式',
            '激活途径',
            '支付时间'
        );
        $exportData[] = $firstRow;
        // 获取学生其他信息
        foreach($payList as &$student) {
            $arr = array(
                $student['realname'],
                $student['class_name'],
                $student['username'],
                $student['name'],
                $student['price'],
                $student['active'],
                $student['pay_way'],
                $student['paytime'],
            );
            $exportData[] = $arr;
        }
        $widthParams = array(
            array(
                'index' => 'B',
                'width' => 20
            ),
            array(
                'index' => 'C',
                'width' => 20
            ),
            array(
                'index' => 'D',
                'width' => 16
            ),
            array(
                'index' => 'E',
                'width' => 16
            ),
            array(
                'index' => 'F',
                'width' => 20
            ),
            array(
                'index' => 'G',
                'width' => 16
            ),
            array(
                'index' => 'H',
                'width' => 20
            )
        );
        exportExcel('激活记录表', $exportData, $widthParams);
    }

    // 一体机管理
    public function aio(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "aio");
    }
    public function save_aio_action(){
        $this->load->model('aioModel');
        $aioId = $this->post("id") ? $this->post("id") : 0;
        $facesluiceId = $this->post("facesluice_id");
        $desc = $this->post("desc");
        // var_export(!$deviceSn);exit;
        // 数据检查
        if(!$facesluiceId) throw new Exception("请填写一体机ID");
        // 检查本校是否有重复一体机
        if($this->aioModel->check_aio_facesluice_id_exists($this->rmxSchool['id'], $this->campusInfo['id'], $facesluiceId, $aioId)) {
            throw new Exception("一体机ID已存在");
        }
        // 入库
        $data['facesluice_id'] = $facesluiceId;
        $data['desc'] = $desc;
        if($aioId) {
            $this->db->update(AioModel::$aioTable, $data,"id='{$aioId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['createtime'] = date('Y-m-d H:i:s');
            $this->db->insert(AioModel::$aioTable, $data);
            $insertAioId = $this->db->insert_id();
            // 添加一体机任务，遍历全校区有录入人脸的学生
            $studentParams['schoolId'] = $this->rmxSchool['id'];
            $studentParams['campusId'] = $this->campusInfo['id'];
            $studentParams['isDelete'] = 0;
            $studentParams['hasFaceImage'] = 1;
            $studentList = $this->schoolModel->get_student_list($studentParams);
            $insertTaskBatch = array();
            foreach($studentList as $student) {
                array_push($insertTaskBatch, array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'aio_id' => $insertAioId,
                    'facesluice_id' => $facesluiceId,
                    'user_id' => $student['id'],
                    'user_name' => $student['realname'],
                    'user_face_image' => $student['face_image'],
                    'user_type' => AIO_USER_TYPE_STUDENT,
                    'task_type' => AIO_TASK_TYPE_ADD,
                    'task_state' => AIO_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
            }
        }
        $msg = $aioId ? '修改一体机成功' : '添加一体机成功';
        exit(json($msg, true));
    }
    // 获取一体机列表
    public function get_aio_list(){
        $this->load->model('aioModel');
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->aioModel->get_aio_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $list = $this->aioModel->get_aio_list($data);
        // 返回值
        exit(admin_table_data($total, $list));
    }
    // 删除一体机
    public function delete_aio_action() {
        $this->load->model('aioModel');
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1
        );
        $this->db->update(AioModel::$aioTable, $data, array('id' => $id));
        // 删除对应的任务
        $this->db->update(AioModel::$aioTaskTable, $data, array('aio_id' => $id));

        exit(json('删除成功', true));
    }
    // 一体机任务列表
    public function aio_task(){
        $this->load->model('aioModel');
        // 获取一体机列表
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $this->aioList = $this->aioModel->get_aio_list($data);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "aio_task");
    }
    // 获取一体机任务列表
    public function get_aio_task_list(){
        $this->load->model('aioModel');
        if($this->get('aio_id')) {
            $totalParams['aioId'] = $this->get('aio_id');
            $data['aioId'] = $this->get('aio_id');
        }
        if($this->get('realname')) {
            $totalParams['realname'] = $this->get('realname');
            $data['realname'] = $this->get('realname');
        }
        if($this->get('task_type')) {
            $totalParams['taskType'] = $this->get('task_type');
            $data['taskType'] = $this->get('task_type');
        }
        if($this->get('task_state')) {
            $totalParams['taskState'] = $this->get('task_state');
            $data['taskState'] = $this->get('task_state');
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->aioModel->get_aio_task_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $list = $this->aioModel->get_aio_task_list($data);
        foreach($list as $key => $item) {
            // 转换设备类型
            $list[$key]['user_type_format'] = transform_aio_user_type($item['user_type']);
            $list[$key]['task_type_format'] = transform_aio_task_type($item['task_type']);
            $list[$key]['task_state_format'] = transform_aio_task_state($item['task_state']);
            $list[$key]['task_state_desc'] = $this->transform_aio_task_state_desc($item['task_state_desc']);
        }
        // 返回值
        exit(admin_table_data($total, $list));
    }

    private function transform_aio_task_state_desc($desc) {
        switch($desc) {
            case 'Get pic Person Feature err, please change a pic':
                return '<span class="text-danger">未检测到人脸</span>';
            case 'get pic and connect URI IP error':
                return '<span class="text-danger">设备DNS错误</span>';
            case 'get URI pic data len too long':
                return '<span class="text-danger">图片大小超过1M</span>';
            default:
                return $desc;
        }
    }

    // 智能门锁管理
    public function smart_lock(){
        // 获取班级列表
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $this->classList = $this->classesModel->get_class_list($params);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "smart_lock");
    }
    public function save_smart_lock_action(){
        $this->load->model('schoolModel');
        $id = $this->post("id") ? $this->post("id") : 0;
        $deviceId = trim($this->post("device_id"));
        $classId = $this->post("class_id") ? $this->post("class_id") : 0;
        $token = trim($this->post("token"));
        $ip = trim($this->post("ip"));
        $deviceType = trim($this->post("device_type"));
        $type = $this->post('type') ? $this->post('type') : 1;
        // var_export(!$deviceSn);exit;
        // 数据检查
        // if(!$deviceId) throw new Exception("请填写门锁设备ID");
        if(!$classId) throw new Exception("请选择关联班级");
        // if(!$token) throw new Exception("请填写接口token");
        // if(!$ip) throw new Exception("请填写接口ip");
        // if(!$deviceType) throw new Exception("请填写门锁设备类型");
        // 信锐门锁需要判断
        if($type == SMART_LOCK_TYPE_XINRUI) {
            // 检查本校是否有重复智能门锁
            if($this->schoolModel->check_smart_lock_device_id_exists($this->rmxSchool['id'], $this->campusInfo['id'], $deviceId, $id)) {
                throw new Exception("设备ID不能重复");
            }
        }
       
        // if($this->schoolModel->check_smart_lock_class_id_exists($this->rmxSchool['id'], $this->campusInfo['id'], $classId, $id)) {
        //     throw new Exception("关联班级不能重复");
        // }
        
        // 入库
        $data['device_id'] = $deviceId;
        $data['class_id'] = $classId;
        $data['token'] = $token;
        $data['ip'] = $ip;
        $data['device_type'] = $deviceType;
        $data['type'] = $type;
        if($id) {
            $this->db->update(SchoolModel::$smartLockTable, $data,"id='{$id}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['createtime'] = date('Y-m-d H:i:s');
            $this->db->insert(SchoolModel::$smartLockTable, $data);
        }
        $msg = $id ? '修改智能门锁成功' : '添加智能门锁成功';
        exit(json($msg, true));
    }
    // 获取智能门锁列表
    public function get_smart_lock_list(){
        $this->load->model('schoolModel');
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->schoolModel->get_smart_lock_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $list = $this->schoolModel->get_smart_lock_list($data);
        if($list) {
            // 获取班级列表
            $classParams['schoolId'] = $this->rmxSchool['id'];
            $classParams['campusId'] = $this->campusInfo['id'];
            $classParams['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键值
            $classList = array_value_to_key($classList, 'id');
            foreach($list as &$item) {
                // 获取班级名称
                if(isset($classList[$item['class_id']])) {
                    $item['class_name'] = $classList[$item['class_id']]['class_name'];
                } else {
                    $item['class_name'] = '';
                }
                // 类型
                $item['typeName'] = $this->_get_smart_lock_type_name($item['type']);
            }
        }

        // 返回值
        exit(admin_table_data($total, $list));
    }
    private function _get_smart_lock_type_name($type) {
        switch($type){		
			case SMART_LOCK_TYPE_XINRUI:
				return '信锐门锁';
            case SMART_LOCK_TYPE_ELECTR:
                return '电磁门锁';
			default: 
				return '';
		}
    }
    // 删除智能门锁
    public function delete_smart_lock_action() {
        $this->load->model('schoolModel');
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1
        );
        $this->db->update(SchoolModel::$smartLockTable, $data, array('id' => $id));
    
        exit(json('删除成功', true));
    }

    // 学生门锁白名单管理
    public function smart_lock_student_white_list(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);


        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);
        

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "smart_lock_student_white_list");
    }

    // 获取学生列表
    public function get_student_list_for_smart_lock(){
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
        // 是否白名单筛选
        // var_export($this->get("white") );exit;
        if($this->get("white") === '1' || $this->get("white") === '0') $totalParams['isWhiteList'] = $data['isWhiteList'] = trim($this->get("white"));
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $totalParams['classId'] = $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $total = $this->schoolModel->get_student_list_join_smart_lock_white_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        $data['orderBy'] = '`id` DESC';
        $studentList = $this->schoolModel->get_student_list_join_smart_lock_white_list($data);

        // 获取学生其他信息
        foreach($studentList as &$student) {
            $classInfo = $this->classesModel->get_class_info($student['class_id']);
            $student['className'] = $classInfo['class_name'] ? $classInfo['class_name'] : '';
            // 判断当前用户有没编辑权限
            $student['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && !in_array($student['class_id'], $this->rmxUser['classIdArr'])) {
                $student['role_change'] = false;
            }
            // 是否限制增值功能
            if($student['white_list_id'] != NULL) {
                $student['isWhiteList'] = '<label class="text-success">是</label>';
            } else {
                $student['isWhiteList'] = '<label class="text-danger">否</label>';
            }
        }
        // echo '<pre>';var_export($studentList);exit;
        // 返回值
        exit(admin_table_data($total, $studentList));
    }

    // 添加白名单操作
    public function add_smart_lock_student_white_list_action() {
        $studentId = $this->post('student_id');
        // var_export($studentId);exit;
        $studentInfo = $this->schoolModel->get_student_info($studentId);
        if(empty($studentInfo)) {
            throw new Exception('参数错误');
        }
        // 判断是否已存在学生白名单
        $whiteListInfo = $this->schoolModel->get_smart_lock_student_white_list_info_by_student_id($studentId);
        if(empty($whiteListInfo)) {
            $data = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'class_id' => $studentInfo['class_id'],
                'student_id' => $studentId,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            );
            $this->db->insert(SchoolModel::$smartLockStudentWhiteListTable, $data);
        }
      
        exit(json('添加白名单成功', true));
    }

    // 移除白名单操作
    public function delete_smart_lock_student_white_list_action() {
        $studentId = $this->post('student_id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(SchoolModel::$smartLockStudentWhiteListTable, $data, "student_id={$studentId}");
        exit(json('移除白名单成功', true));
    }

    // 批量添加白名单操作
    public function add_smart_lock_student_white_list_batch_action() {
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要更新的学生");
        }
        // 获取学生列表
        $studentParams['schoolId'] = $this->rmxSchool['id'];
        $studentParams['campusId'] = $this->campusInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        // 使用id作为键值
        $studentList = array_value_to_key($studentList, 'id');
        $insertBatch = array();
        foreach($idArr as $studentId) {
            // 判断是否已存在学生白名单
            $whiteListInfo = $this->schoolModel->get_smart_lock_student_white_list_info_by_student_id($studentId);
            if(empty($whiteListInfo)) {
                $data = array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'class_id' => isset($studentList[$studentId]) ? $studentList[$studentId]['class_id'] : 0,
                    'student_id' => $studentId,
                    'is_delete' => 0,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                );
                array_push($insertBatch, $data);
            }
        }
        if($insertBatch) {
            $this->db->insert_batch(SchoolModel::$smartLockStudentWhiteListTable, $insertBatch);
        }
        exit(json('批量添加成功', true));
    }
    // 批量移除白名单操作
    public function delete_smart_lock_student_white_list_batch_action() {
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要更新的学生");
        }
        $updateBatch = array();
        foreach($idArr as $studentId) {
            $data = array(
                'student_id' => $studentId,
                'updatetime' => date('Y-m-d H:i:s'),
                'is_delete' => 1
            );
            array_push($updateBatch, $data);
        }
        if($updateBatch) {
            $this->db->update_batch(SchoolModel::$smartLockStudentWhiteListTable, $updateBatch, 'student_id');
        }
        exit(json('批量移除成功', true));
    }

    // 开锁记录页面
    public function unlock_record(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);


        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);
        

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "school". DIRECTORY_SEPARATOR. "unlock_record");
    }

    // 获取开锁记录
    public function get_smart_lock_unlock_record_list(){
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));
    
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $totalParams['classId'] = $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $total = $this->schoolModel->get_smart_lock_unlock_record_list($totalParams);
        // var_export($total);exit;
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 按id倒序
        $data['orderBy'] = '`createtime` DESC';
        $list = $this->schoolModel->get_smart_lock_unlock_record_list($data);

        if($list) {
            // 获取班级列表
            $classParams['schoolId'] = $this->rmxSchool['id'];
            $classParams['campusId'] = $this->campusInfo['id'];
            $classParams['isDelete'] = 0; 
            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键值
            $classList = array_value_to_key($classList, 'id');
            // 获取其他信息
            foreach($list as &$item) {
                $item['className'] = isset($classList[$item['class_id']]) ? $classList[$item['class_id']]['class_name'] : '';
                // 用户类型
                $item['userTypeName'] = transform_user_type($item['user_type']);
            }
        }

        // echo '<pre>';var_export($studentList);exit;
        // 返回值
        exit(admin_table_data($total, $list));
    }
}